//
//  SocketTelecom.m
//  ZZChatiPhone
//
//  Created by zzsoft on 16/1/5.
//  Copyright © 2016年 zzsoft. All rights reserved.
//

#import "SocketTelecom.h"

//long const TAG_SOCKET_START = 1;
long const TAG_SOCKET_END_Telecom = 2;

@interface SocketTelecom()<GCDAsyncSocketDelegate>
@property(nonatomic,strong)GCDAsyncSocket *asyncSocket;
@property(nonatomic,strong)NSArray *proxyServerList;
@property(nonatomic,assign)NSInteger index;
@end
@implementation SocketTelecom
+ (SocketTelecom*)sharedManager {
    static dispatch_once_t once;
    static SocketTelecom *sharedManager;
    dispatch_once(&once, ^ {
        sharedManager = [[SocketTelecom alloc] init];
    });
    return sharedManager;
}

- (id) init
{
    self = [super init];
    if (self) {
        _asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    }
    return self;
}

-(void)connectToHost:(NSString *)host onPort:(uint16_t)port{
    if(_asyncSocket){
        NSError *error = nil;
        [_asyncSocket connectToHost:host onPort:port withTimeout:kTimeout error:&error];
    }
}

-(void)disConnect{
    [_asyncSocket disconnect];
    //[_asyncSocket disconnectAfterReadingAndWriting];
}

-(void)writeData:(NSData *)data{
    [_asyncSocket writeData:data withTimeout:-1 tag:0];
    [_asyncSocket readDataToData:[kEndDataStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:TAG_SOCKET_END_Telecom];
}

-(void)didConnect:(NSArray *)proxyServerList{
    /*
    _index = 0;
    if(proxyServerList&&proxyServerList.count >0){
        NSError *error = nil;
        _proxyServerList = proxyServerList;
        ProxyServer *server = proxyServerList[_index];
        [_asyncSocket connectToHost:server.host onPort:server.port withTimeout:kTimeout error:&error];
    }*/
}

-(BOOL)isConnect{
    return [_asyncSocket isConnected];
}

#pragma mark - AsyncSocketDelegate
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    NSLog(@"电信连接成功---%@----%d",host,port);
    if(_isConnectBlock){
        self.isConnectBlock(YES,nil);
    }
    [sock readDataToData:[kEndDataStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:TAG_SOCKET_END_Telecom];
}
/*
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    NSLog(@"电信连接失败:%@",[err localizedDescription]);
    if(_isFirst&&_proxyServerList&&_proxyServerList.count -1 >_index){
        _index++;
        ProxyServer *server = _proxyServerList[_index];
        NSError *error = nil;
         [_asyncSocket connectToHost:server.host onPort:server.port withTimeout:kTimeout error:&error];
    }else if(_isConnectBlock){
        NSLog(@"电信连接中");
        self.isConnectBlock(NO,err);
    }
}
*/
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
    NSLog(@"---发送数据的 taG---%ld",tag);
    [sock readDataToData:[kEndDataStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:TAG_SOCKET_END_Telecom];
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    NSLog(@"---读取数据的 taG---%ld",tag);
    if(tag == TAG_SOCKET_END_Telecom){
        @try {
            if(data==NULL)
            {
                [sock readDataToData:[kEndDataStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:TAG_SOCKET_END_Telecom];
                return;
            }
            if([data length]<4)
            {
               [sock readDataToData:[kEndDataStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:TAG_SOCKET_END_Telecom];
                return;
            }
            NSData *dataContet=[data subdataWithRange:NSMakeRange(4, [data length]-4)];
            if(dataContet==NULL)
            {
                [sock readDataToData:[kEndDataStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:TAG_SOCKET_END_Telecom];
                return;
            }
            NSString *xmlString = [[NSString alloc] initWithData:dataContet encoding:NSUTF8StringEncoding];
            if(xmlString==NULL)
            {
                [sock readDataToData:[kEndDataStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:TAG_SOCKET_END_Telecom];
                return;
            }
            if(self.messageBlock){
                xmlString=[xmlString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
                if(xmlString==NULL)
                {
                    [sock readDataToData:[kEndDataStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:TAG_SOCKET_END_Telecom];
                    return;
                }
                NSRange start=[xmlString rangeOfString:@"{"];
                xmlString=[xmlString substringFromIndex:start.location];
                NSDictionary *resdict=[NSJSONSerialization JSONObjectWithData:[xmlString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
                NSLog(@"resdict is %@.",resdict);
                if(resdict==NULL||[resdict count]==0)
                {
                    NSLog(@"---读取数据的 taG--- resdict is null.");
                    [sock readDataToData:[kEndDataStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:TAG_SOCKET_END_Telecom];
                    return;
                }
                self.messageBlock(resdict);
            }

        }
        @catch (NSException *exception) {
            NSLog(@"exception is %@.",exception);
        }
        @finally {
            
        }

    }
    [sock readDataToData:[kEndDataStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:TAG_SOCKET_END_Telecom];
}
@end